package com.lagou.controller;

import com.lagou.code.CodeDubboService;
import com.lagou.po.UserPO;
import com.lagou.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @AUTHOR: yb.feng
 * @DATE: 2020/6/30 21:36
 * @DESC:
 */
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;

    @Reference
    private CodeDubboService codeDubboService;

    @RequestMapping("/user/register/{email}/{password}/{code}")
    public String register(@PathVariable String email, @PathVariable String password, @PathVariable String code){
        Integer status = codeDubboService.validateCode(email, code);
        if (status == null || status == 1){
            return "验证码错误";
        }
        if (status == 2){
            return "验证码过期";
        }
        userService.saveUser(new UserPO(email, password));
        return "注册成功";
    }

    @RequestMapping("/user/login/{email}/{password}")
    @ResponseBody
    public String login(HttpServletResponse response, @PathVariable String email, @PathVariable String password){
        UserPO user = userService.findByUserName(email);
        if (user == null){
            return "该用户不存在";
        }
        if (!password.equals(user.getPassword())){
            return "用户名或密码错误";
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        userService.saveToken(email, token);
        email = email.replace("@", "-");
        Cookie cookie = new Cookie(email, token);
        cookie.setDomain("www.test.com");
        response.addCookie(cookie);
        return email;
    }

    @RequestMapping("/user/isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email){
        UserPO user = userService.findByUserName(email);
        return user != null;
    }

    @RequestMapping("/user/info/{token}")
    public String getEmail(@PathVariable String token){
        return userService.findEmailByToken(token);
    }

    @RequestMapping("/user/get")
    public String getUserName(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            return name.replace("-", "@");
        }
        return null;
    }

}
